import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:quick_widget/drop_menu_container.dart';
import 'package:saas_order_meal/model/elder_info_data.dart';
import 'package:saas_order_meal/model/week_food_model.dart';
import 'package:saas_order_meal/net/net_response/elder_month_record.dart';
import 'package:saas_order_meal/utils/meal_ext_utils.dart';
import 'package:saas_order_meal/viewmodel/regular_menu_contain_view_model.dart';

import '../model/order_request_data.dart';
import '../ui/apply_meal_by_week_page.dart';

class ByWeekFoodMenuViewModel extends BaseViewModel {
  final OrderRequestData orderData;
  var weekIndex = 0;
  var menuModel = WeekFoodModel();
  List<ElderMonthRecordList> weekData = [];
  List<DaySelectFood> selectDayFood = [];
  late OnFoodSelectListener listener;
  var controller = DropMenuController();
  var totalPrice = 0.0;
  var totalNum = 0;

  ByWeekFoodMenuViewModel(BuildContext? context, {required this.orderData})
      : super(context) {
    weekIndex = orderData.weekDay - 1;
  }

  Future<void> getMonthData() async {
    showLoadingState();
    try {
      var first = orderData.weekList.first;
      var data = await menuModel.getElderMonth(
          elderHumanId: orderData.elderHumanId, startDate: first, showDay: 7);
      weekData = data.list ?? [];
      initHasOrdered();
      showContent();
    } catch (e) {
      showErrorState(e.toNetError());
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    getMonthData();

    listener = (dayFood) {

      var filterList = selectDayFood.takeWhere<DaySelectFood>((element) => element.date==dayFood.date);
      if(filterList.isNotEmpty){
        if(dayFood.selectFood.isNotEmpty){
          // filterList.first.date = dayFood.date;
          // filterList.first.price = dayFood.price;
          // filterList.first.selectFood = dayFood.selectFood;
          selectDayFood.remove(filterList.first);
          selectDayFood.add(dayFood);
        }else{
          selectDayFood.remove(filterList.first);
        }
      }else{
        selectDayFood.add(dayFood);
      }
      selectDayFood.sort((o1,o2){
        return o1.date.compareTo(o2.date);
      });
      _getTotalPrice();
      // print(selectDayFood.map((e) => "${e.date}===${e.selectFood.map((food) => food.timeSectionName).join(",")}"));
      notifyListeners();
    };
  }


  void _getTotalPrice(){
    totalPrice = 0.0;
    totalNum = 0;
    for(var item in selectDayFood){

      totalPrice =  (totalPrice.d+item.price.d).toDouble();
      totalNum+=item.selectFood.length;
    }
  }

  Widget bottomContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            CommonText('已选商品').setWeight(1),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Icon(
                  Icons.delete_outline,
                  color: Colors.grey[800],
                  size: 18,
                ),
                CommonText('清空', textSize: 14, textColor: Colors.grey[800]!)
              ],
            ).onTap(() {
              clearSelected();
              notifyListeners();
              controller.hide();
            })
          ],
        ).addToContainer(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16)),
        ListView.separated(
          padding: EdgeInsets.symmetric(horizontal: 16),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            var item = selectDayFood[index];
            return selectMealItem(item);
            // return Container();
          },
          separatorBuilder: (context, index) {
            return Divider();
          },
          itemCount: selectDayFood.length,
        ).setWeight(1)
      ],
    ).addToContainer(color: Colors.white,constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height*0.6
    ));
  }

  void clearSelected() {
    if (selectDayFood.isEmpty) {
      return;
    }
    for (var item in selectDayFood) {
      for (var meal in item.selectFood) {
        for(var food in meal.selectFood){
          food.status = 0;
          food.number = 0;
        }
      }
    }
    selectDayFood.clear();
    notifyListeners();
  }

  Widget selectMealItem(DaySelectFood dayMeal) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        CommonText(dayMeal.date,fontWeight: FontWeight.bold,textSize: 18),
        ...dayMeal.selectFood.map((item) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 8,
              ),
              Row(
                children: [
                  CommonText(
                      "${item.timeSectionName}",
                      textSize: 17,
                      textColor: Colors.grey[700]!,
                      fontWeight: FontWeight.bold)
                      .setWeight(1),
                  CommonText("¥${item.price}",
                      textSize: 17, textColor: Colors.red),
                ],
              ),
              Container(
                height: 15,
              ),
              CommonText(
                  item.selectFood.map((e) => "${e.goodsName}x${e.number}").join("、"),
                  textColor: Colors.grey[800]!,
                  textSize: 17),
              Container(
                height: 15,
              ),
            ],
          );
        }).toList(),
        Container(height: 8,color: Colors.grey[200],)
      ],
    );
  }

  Future<void> toApplySubmit() async {
    if(selectDayFood.isEmpty){
      return;
    }
    orderData.weekSelectFood = selectDayFood;
    orderData.totalPrice = totalPrice;
    var data = await Go().push(ApplyMealByWeekPage(orderData: orderData));
    if(data!=null){
      Go().pop(result: "true");
    }
  }

  void initHasOrdered() {
    var item = weekData[weekIndex];
    List<int> hasMeals = [];
    if(item.breakfast!=null){
      hasMeals.add(1);
    }
    if(item.lunch!=null){
      hasMeals.add(2);
    }
    if(item.dinner!=null){
      hasMeals.add(3);
    }
    if(item.breakfastSp!=null){
      hasMeals.add(4);
    }
    if(item.lunchSp!=null){
      hasMeals.add(5);
    }
    if(item.dinnerSp!=null){
      hasMeals.add(6);
    }
    var date = item.date!.substring(0,10);

    orderData.weekHasOrderedMeal![date] = hasMeals;
  }
}
